import React, { Component } from 'react'
import {
    Card,
    Input,
    Button,
    Select,
    Table,
    message,
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import LinkButton from '../../../components/link-button'
import {reqProducts, reqSearchProducts, reqUpdateStatus, deleteProduct} from '../../../api'
import {PAGE_SIZE} from '../../../utils/constants'

// 选择框项目
const {Option} = Select

// prodect的默认子路由组件
export default class ProductHome extends Component {

    state = {
        products: [], // 商品数据
        total: 0, // 商品总数量
        loadingFlg: false,
        searchName: '', // 搜索关键字
        searchType: 'productName', // 搜索的类型
        pageNum: 1,
        buttonDisabled: true,
        pageName: "商品管理",
    }

    // 获取指定页码商品数据
    getProducts = async (pageNum) => {
        // 保存页码信息
        this.pageNum = pageNum
        // 发送ajax请求前loading
        this.setState({loadingFlg: true})
        const {searchType, searchName} = this.state
        let reponse;
        // 没有关键字的情况下
        if (searchName === '') {
            console.log(pageNum, PAGE_SIZE)
            reponse = await reqProducts(pageNum, PAGE_SIZE)
        } else {
            reponse = await reqSearchProducts({pageNum, pageSize:PAGE_SIZE, searchName, searchType})
        }

        // 请求结束后取消loading
        this.setState({loadingFlg: false})

        const result = reponse.data
        console.log("result", result)
        if (result.status === 0) {
            const {total,list} = result.data.products
            this.setState({
                total,
                products: list,
                pageNum,
                buttonDisabled: false,
            })
        } else if (result.status === 2) {
            message.error("您没有使用" + this.state.pageName + "的权限")
        } else {
            message.error(result.message)
        }
    }

    // 根据名称或者描述搜索商品
    searchProductBy = async () => {
        const {searchType, searchName, pageNum} = this.state
        // 发送ajax请求前loading
        this.setState({loadingFlg: true})
        const reponse = await reqSearchProducts({pageNum:1, pageSize:PAGE_SIZE, searchName, searchType})
        // 请求结束后取消loading
        this.setState({loadingFlg: false})
        const result = reponse.data
        if (result.status === 0) {
            this.pageNum = 1
            const {total,list} = result.data.list
            // 检索成功后将当前页重新定位至1
            this.setState({
                total,
                products: list,
            })
            
        } else {
            message.error('获取商品信息失败')
        }
    }

    // 更改商品状态
    updateStatus = async (status, procuctId) => {
        const reponse = await reqUpdateStatus(procuctId, status)
        const result = reponse.data
        if (result.status === 0) {
            message.success('更新商品状态成功')
            this.getProducts(this.pageNum)
        } else {
            message.error('更改商品状态失败')
        }
        
    }

    // 删除商品
    deleteProduct = async (product) => {
        let productId = product.id
        const reponse  = await deleteProduct(productId);
        const result = reponse.data
        if (result.status === 0) {
            message.success('商品删除成功')
            this.getProducts(this.pageNum)
        } else {
            message.error(result.message)
        }
    }

    // 组件挂载之后发送请求获取列表数据
    componentDidMount () {
        this.getProducts(1)
    }

    render() {

        // 取出state中的数据
        const {products, total, loadingFlg, searchType, searchName, buttonDisabled} = this.state
        console.log(this.pageNum,"thispageNum")

        const columns = [
            {
              title: '商品名称',
              dataIndex: 'productName',
              width: 230
            },
            {
              title: '商品描述',
              dataIndex: 'productDesc',
            },
            {
              title: '价格',
              dataIndex: 'price',
              width: 130,
              render: (price) => '¥' + price // 不指定render就显示dataIndex绑定的值，指定了就显示render的值
            },
            {
                title: '状态',
                dataIndex: 'status',
                width: 180,
                render: (status, product) => {
                    return (
                        <span>
                            <span style={{marginRight: 55}}>{status === 1 ? '在售' : '售罄'}</span>
                            <Button type='primary' size='small' onClick={() => this.updateStatus(status === 1 ? 2 : 1, product.id)}>{status === 1 ? '下架' : '上架'}</Button>
                        </span>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: 'address',
                width: 180,
                render: (_, product) => {
                    return (
                        <span>
                            {/* <LinkButton onClick={() => this.props.history.push('/product/addUpdate', product)}>修改</LinkButton> */}
                            <LinkButton onClick={() => this.deleteProduct(product)}>删除</LinkButton>
                        </span>
                    )
                }
            },
          ]

        // 标题内容
        const title = (
            <span>
                <Select value={searchType} style={{width:'120px'}} onChange={value => this.setState({searchType:value})}>
                    <Option value='productName'>按名称搜索</Option>
                    <Option value='productDesc'>按描述搜索</Option>
                </Select>
                <Input placeholder='请输入关键字' style={{width: '180px',margin: '0 10px'}} onChange={e => this.setState({searchName:e.target.value})}/>
                <Button type='primary' disabled={buttonDisabled} onClick={this.searchProductBy}>搜索</Button>
            </span>
        )

        // 添加按钮
        const extra = (
            <Button type='primary' disabled={true} icon={<PlusOutlined />} onClick={() => this.props.history.push('/product/addUpdate')}>添加商品</Button>
        )

        return (
            // ps.阿里云oss过期了，木的钱续费，所以只能把这个画面锁上了
            <Card title={title} extra={extra} style={{ width: 1680 ,height: 780}}>
                <Table 
                    rowKey="id"
                    columns={columns}
                    dataSource={products}
                    bordered
                    loading={loadingFlg}
                    pagination={{current: this.pageNum, total,defaultPageSize: PAGE_SIZE, showQuickJumper: true}}
                    onChange={(page) => this.getProducts(page.current)}
                    />
            </Card>
        )
    }
}
